package org.girllee.boot.controller

import javax.servlet.http.HttpServletResponse
import org.springframework.web.bind.annotation.{GetMapping, RestController}

import scala.util.Random

@RestController
class ScalaController {
  @GetMapping(path = Array("demo"))
  def demo={"This is scala first web application."}


  @GetMapping(path=Array("push/sse"))
  def push(resp:HttpServletResponse) ={
    val r = new Random()
    resp.setContentType("text/event-stream")
    resp.setCharacterEncoding("UTF-8")
    resp.setHeader("Cache-Control","no-cache")

    var run = true
    while(run){
      try{
        val n = r.nextLong()
        Thread.sleep(1000)
        val rtn = "event:evt\ndata:{\"val\":" + n.toString +"}\n\n"
        val pw = resp.getWriter
        println(rtn)
        pw.write(rtn)
        run = !pw.checkError();
      }catch {
        case ex: Exception=>ex.getMessage;
      }
    }
  }



}
